//
//  HMComposeView.swift
//  swift-新浪微博0
//
//  Created by 赵玉忠 on 16/9/7.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import pop

class HMComposeView: UIView {
    
    
    /// 外界传入的控制器，用于弹出新控制器的
    var target: UIViewController?
    
    lazy var buttons: [UIButton] = [UIButton]()
    
    var infoArray: NSArray?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        //        let data = UIImagePNGRepresentation(image!)! as NSData
        //        data.write(toFile: "/Users/heima/Desktop/bug.png", atomically: true)
        
        // 设置大小
        frame.size = UIScreen.main.bounds.size
        // 1. 添加控件
        addSubview(bgImage)
        addSubview(sloganImage)
        
        // 2. 添加约束
        bgImage.snp_makeConstraints { (make) in
            make.edges.equalTo(self)
        }
        sloganImage.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self)
            make.top.equalTo(100)
        }
        
        addChildButtons()
    }
    
    /// 添加子按钮
    func addChildButtons() {
        
        // 按钮的宽度
        let itemW: CGFloat = 80
        let itemH: CGFloat = 110
        // 求出每按钮之间的间距
        let itemMargin = (HMScreenW - 3 * itemW) / 4
        
        // 读取 compose.list
        let path = Bundle.main.path(forResource: "compose.plist", ofType: nil)!
        let array = NSArray(contentsOfFile: path)!
        // 记录当前的模型数组信息
        infoArray = array
        for i in 0..<array.count {
            let button = HMComposeButton(textColor: UIColor.darkGray, fontSize: 14)
            // 添加点击事件
            button.addTarget(self, action: #selector(childButtonClick(button:)), for: UIControlEvents.touchUpInside)
            // 取出对应位置的字典
            let dict = array[i] as! [String: String]
            // 设置图标与文字
            button.setImage(UIImage(named: dict["icon"]!), for: UIControlState.normal)
            button.setTitle(dict["title"]!, for: UIControlState.normal)
            // 设置大小
            button.frame.size = CGSize(width: itemW, height: itemH)
            
            // 1. 求出按钮在第几列
            let col = i % 3
            // 2. 求出按钮在第几行
            let row = i / 3
            
            // 通过列数求出x值
            let x = CGFloat(col) * itemW + CGFloat(col + 1) * itemMargin
            // 通过行数求出y值
            let y = CGFloat(row) * itemH + HMScreenH
            // 设置按钮的位置
            button.frame.origin = CGPoint(x: x, y: y)
            
            addSubview(button)
            // 使用数组保存按钮
            buttons.append(button)
        }
    }
    
    
    /// 当前控件被添加到某个视图上之后就会调用
    /// 但是，这个控件从父控件中移除也会调用
    /// 而且，这个方法代表是当前控件被移动到父控件之后
    /// 而我们要做的事情就是做一个弹性动画 --> 要在界面显示出来之后去做
    //    override func didMoveToSuperview() {
    //
    //    }
    
    
    /// 供外界调用，将当前控件显示出来
    func show(target: UIViewController) {
        self.target = target
        //        let window = UIApplication.shared.keyWindow
        //        window?.addSubview(self)
        self.target?.view.addSubview(self)
        
        for (index,button) in buttons.enumerated() {
            // 之后去执行动画
            anim(button: button, index: index, isUp: true)
        }
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        
        for (index,button) in buttons.reversed().enumerated() {
            anim(button: button, index: index, isUp: false)
            //            // 之后去执行动画
            //            let anim = POPSpringAnimation(propertyNamed: kPOPViewCenter)
            //            anim?.toValue = NSValue.init(cgPoint: CGPoint(x: button.center.x, y: button.center.y + 350))
            //            anim?.springBounciness = 12
            //            anim?.springSpeed = 10
            //            // 动画的开始执行时间
            //            anim?.beginTime = CACurrentMediaTime() + Double(index) * 0.025
            //            button.pop_add(anim, forKey: nil)
        }
        
        // Swift 3.0 中dispatch_after
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.4) {
            self.removeFromSuperview()
        }
    }
    
    /// 执行按钮的动画
    ///
    /// - parameter button: 要执行动画的对象
    /// - parameter index:  当前按钮的索引
    /// - parameter isUp:   代表是执行向上的动画还是向下
    func anim(button: UIButton, index: Int, isUp: Bool) {
        let anim = POPSpringAnimation(propertyNamed: kPOPViewCenter)
        anim?.toValue = NSValue.init(cgPoint: CGPoint(x: button.center.x, y: button.center.y + (isUp ? -350 : 350) ))
        anim?.springBounciness = 12
        anim?.springSpeed = 10
        // 动画的开始执行时间
        anim?.beginTime = CACurrentMediaTime() + Double(index) * 0.025
        button.pop_add(anim, forKey: nil)
    }
    
    // MARK: - 监听事件
    
    @objc private func childButtonClick(button: UIButton) {
        // 遍历所有的按钮
        UIView.animate(withDuration: 0.5, animations: {
            for value in self.buttons {
                // 如果当前点击的按钮与当前遍历到的按钮是同一个按钮的话，那么就将该按钮放大
                if button == value {
                    // 放大
                    value.transform = CGAffineTransform.init(scaleX: 2, y: 2)
                }else{
                    // 否则缩小
                    value.transform = CGAffineTransform.init(scaleX: 0.2, y: 0.2)
                }
                value.alpha = 0.1
            }
            
        }) { (_) in
            // 动画执行完成调用
            // 弹出控制器
            // 要取对按钮所对应的字典数据
            let index = self.buttons.index(of: button) ?? 0
            let dict = self.infoArray![index] as! [String: String]
            if let name = dict["class"] {
                // 通过类名去初始化类
                let type = NSClassFromString(name)! as! UIViewController.Type
                let vc = type.init()
                self.target?.present(HMNavigationController(rootViewController: vc), animated: true, completion: {
                    print("弹出完成")
                    self.removeFromSuperview()
                })
            }
        }
    }
    
    // MARK: - 懒加载控件
    private lazy var bgImage: UIImageView = {
        let imageView = UIImageView(image: UIImage.getScreenSnap()?.applyLightEffect())
        return imageView
    }()
    
    // compose_slogan
    private lazy var sloganImage: UIImageView = {
        let imageView = UIImageView(image: UIImage(named: "compose_slogan"))
        return imageView
    }()
    
    
    /// 截屏的功能
    ///
    /// - returns: <#return value description#>
    private func getScreenSnap() -> UIImage? {
        
        // 先获取到window
        let window = UIApplication.shared.keyWindow!
        
        // 开启上下文
        // 如果最后一参数传入0的话，会按照屏幕的真实大小来截取，就是不会截取缩放之后的内容
        UIGraphicsBeginImageContextWithOptions(window.bounds.size, false, 0)
        
        // 将window的内容渲染到上下文中
        window.drawHierarchy(in: window.bounds, afterScreenUpdates: false)
        
        // 取到上下文中的图片
        let image = UIGraphicsGetImageFromCurrentImageContext()
        // 关闭上下文
        UIGraphicsEndImageContext()
        // 返回结果
        
        return image
    }
}

